export default function (field) {
  return {
    data() {
      return {
        rangeTime: undefined,
        timeout: null
      }
    },

    created() {
      this.rangeTime = this.getRangeTime();
      this.rangeTimeRunning();
    },

    beforeDestroy() {
      this.clearTimeout();
    },

    methods: {
      rangeTimeRunning() {
        this.clearTimeout();
        let timeout = setTimeout(() => {
          this.timeout = null;
          let rangeTime = this.getRangeTime();
          if (rangeTime === 0) {
            this.toChangeType();
            return;
          }

          this.rangeTime = rangeTime;
          this.rangeTimeRunning();
        }, 500);
        this.timeout = timeout;
      },

      getRangeTime() {
        let data = this[field];
        let type = data.type;
        if (type === 2) {
          return undefined;
        }

        let time;
        if (type === 0) {
          let startTime = data.startTime;
          time = this.$moment(startTime).diff(this.$moment(), 'second');
        } else {
          let endTime = data.endTime;
          time = this.$moment(endTime).diff(this.$moment(), 'second');
        }

        if (time < 0) {
          time = 0;
        } else if (time > 1000 * 3600 - 1) {
          time = 1000 * 3600 - 1;
        }
        return time;
      },

      toChangeType() {
        let data = this[field];
        let type = data.type;
        if (type === 2) {
          this.rangeTime = undefined;
          return;
        }

        if (type === 0) {
          type = 1;
        } else if (type === 1) {
          type = 2;
        }

        this.rangeTime = this.getRangeTime();
        this.rangeTimeRunning();
        data.type = type;
        this.$emit('type-change', type, data);
      },

      clearTimeout() {
        let timeout = this.timeout;
        if (timeout !== null) {
          window.clearTimeout(timeout);
          this.timeout = null;
        }
      }
    }
  };
}
